<template>
  <generate-form
    v-if="formConf.fields.length && formModel"
    ref="generateFormRef"
    class="generateForm"
    :form-conf="formConf"
    :page-form-model="formModel"
  />
</template>

<script setup lang="ts">
import { computed, onMounted, provide, ref } from "vue";
import { useRoute } from "vue-router";
import { getBusinessProcessFormRequest } from "@/api/workflow/workflow";
import GenerateForm from "@/views/formgen/components/GenerateForm/GenerateForm.vue";
import { handleProcessFunc } from "@/views/workflow/task/process/hooks/useHandleProcess";
import { FORM_DISABLED_KEY } from "@/views/formgen/components/GenerateForm/types/constants";

const props = defineProps<{
  taskId?: string;
  operated?: boolean;
  instanceId?: string;
}>();

const formModel = ref<Record<string, any>>({});
const formDataId = ref<string>("");
const formConf = ref({
  labelPosition: "top",
  disabled: false,
  fields: [] as any[]
});

provide(
  FORM_DISABLED_KEY,
  computed(() => !props.operated)
);

const route = useRoute();

const { signatureStatus, adviceStatus, operationBtnList } = handleProcessFunc;

onMounted(() => {
  const taskId = props.taskId || (route.query.taskId as string);
  const instanceId = props.instanceId || (route.query.instanceId as string) || (route.query.procInsId as string);
  formConf.value.disabled = !props.operated;
  getBusinessProcessFormRequest(taskId, instanceId).then((res: any) => {
    if (res.data) {
      const { fields, data } = res.data;
      formConf.value.fields = fields.map((item: any) => item.scheme);
      formModel.value = data.originalData;
      formDataId.value = data.id;
      signatureStatus.value = res.data.signatureStatus || "0";
      adviceStatus.value = res.data.adviceStatus || "1";
      operationBtnList.value = res.data.operationBtnList || [];
    }
  });
});

const generateFormRef = ref<InstanceType<typeof GenerateForm>>();

const getFormModel = () => {
  return generateFormRef.value!.formModel;
};

defineExpose({
  getFormModel,
  formDataId,
  generateFormRef
});
</script>

<style lang="scss" scoped>
.generateForm {
  padding: 0 28px !important;
}

:deep(.el-form-item__label) {
  text-align: left !important;
}
</style>
